package 美团;

public class _240_搜索二维矩阵II {
    public boolean searchMatrix(int[][] matrix, int target) {
        for (int i = 0; i < matrix.length; i++) {
            if (matrix[i][0] > target) break;
            for (int j = 0; j < matrix[i].length; j++) {
                if (matrix[i][j] > target) {
                    break;
                } else if (matrix[i][j] == target) {
                    return true;
                }
            }
        }
        return false;
    }

    // 使用二分查找
    public boolean searchMatrix2(int[][] matrix, int target) {
        for (int i = 0; i < matrix.length; i++) {
            int res = search(matrix[0], target);
            if (res != -1) return true;
        }
        return false;
    }

    public int search(int[] nums, int target) {
        int index = bs(nums, 0, nums.length, target);
        return index;
    }

    private int bs(int[] nums, int begin, int end, int target) {
        if (begin == end) return -1;
        int mid = begin + ((end - begin) >> 1);
        if (nums[mid] == target) return mid;
        if (nums[mid] > target) {
            return bs(nums, mid + 1, end, target);
        } else {

            return bs(nums, begin, mid, target);
        }
    }
}
